package com.rsstuan.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.mortbay.log.Log;

import com.rsstuan.data.TuanGouWebItem;
import com.rsstuan.storage.data.TuanGouItemData;

public class ItemUtils {
	
	private static ItemUtils instance = new ItemUtils();
	
	public static ItemUtils getInstance() {
		return instance;
	}
	
	public static String getImageUrl(String str) {
		try {
			Parser parser = Parser.createParser(str, CharSetUtils.DEFAULT_ENCODING);
			NodeFilter filter = new NodeClassFilter(ImageTag.class);
			NodeList list = parser.extractAllNodesThatMatch(filter);
			if (list.size() > 0) {
				ImageTag tag = (ImageTag) list.elementAt(0);
				return tag.getImageURL();
			}
		}
		catch (Exception e){
			return "";
		}
	
		return "";
	}
	
	public static Double getOrigPrice(String str) {
		Pattern p= Pattern.compile("(原价|价值)￥?\\s*(\\d+\\.?\\d+)元?");
		Matcher m = p.matcher(str);
		if (m.find()) {
			String price = m.group(2);
			try {
				return Double.parseDouble(price);
			}
			catch (Exception e) {
				return null;
			}
		}
		{
	        p = Pattern.compile("(\\d+\\.?\\d+)元");
	        m = p.matcher(str);
	        List<Double> priceList = new ArrayList<Double>();
	        while (m.find()) {
	            String priceStr = m.group(1);
	            Double price = null;
	            try {
	                price = Double.parseDouble(priceStr);
	                priceList.add(price);   
	            } catch (Exception e) {}
	        }
	        if (priceList.size() == 2) {
	        	if (priceList.get(0) > priceList.get(1)) {
	        		return priceList.get(0);
	        	}
	        	else if (priceList.get(1) > priceList.get(0))
	        		return priceList.get(1);
	        }
		}
		{
	        p = Pattern.compile("￥(\\d+\\.?\\d+)");
	        m = p.matcher(str);
	        List<Double> priceList = new ArrayList<Double>();
	        while (m.find()) {
	            String priceStr = m.group(1);
	            Double price = null;
	            try {
	                price = Double.parseDouble(priceStr);
	                priceList.add(price);   
	            } catch (Exception e) {}
	        }
	        if (priceList.size() == 2) {
	        	if (priceList.get(0) > priceList.get(1)) {
	        		return priceList.get(0);
	        	}
	        	else if (priceList.get(1) > priceList.get(0))
	        		return priceList.get(1);
	        }
		}
        
        
        
		return null;
	}
	public static String getAddress(String str) {
	    Pattern p1 = Pattern.compile("地址\\s*(:|：)([^\\s<]+)");
	    Matcher m1 = p1.matcher(str);
	    if (m1.find()) {
	        return m1.group(2);
	    }
	    
	    Pattern p2 = Pattern.compile("\\w+店\\s*(:|：)([^\\s<]+)");
	    Matcher m2 = p2.matcher(str);
        if (m2.find()) {
            return m2.group(0);
        }
        
        Pattern p3 = Pattern.compile("(海淀|朝阳|昌平|怀柔|延庆|西城|东城|崇文)区[^\\s\\)）]+(\\)|）)?\\s\\s+");
        Matcher m3 = p3.matcher(str);
        if (m3.find()) {
            return m3.group(0);
        }
	    return "";
	    
	}
	
	public static Long getEndTime(String str) {
	    Long now = System.currentTimeMillis();
	    Pattern p1 = Pattern.compile("\\d+年\\d+月\\d+日");
	    Matcher m1 = p1.matcher(str);
	    while (m1.find()) {
	        try {
	            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
	            Date d = sdf.parse(m1.group(0));
	            if (d.getTime() > now && (d.getTime()-now < TimeUtils.DAY_MILLISECONDS * 7)) {
	                return d.getTime();
	            }
	        }
	        catch (Exception e) {
	            Log.info("unable to parse endTime = " + m1.group(0));
	        }       
	    }
	    return null;
	}
	
	   public static Long getLeftTime(String str) {
	        Pattern p1 = Pattern.compile("\\d+天\\d+时\\d+分");
	        Matcher m1 = p1.matcher(str);
	        while (m1.find()) {
	            try {
	                SimpleDateFormat sdf = new SimpleDateFormat("dd天HH时mm分");
	                Date d = sdf.parse(m1.group(0));
	                return d.getTime();
	            }
	            catch (Exception e) {
	                Log.info("unable to parse leftTime = " + m1.group(0));
	            }       
	        }
	        return null;
	    }
	
	public static int getOrderNum(String str) {
		
	    Pattern p1 = Pattern.compile("(\\d+)\\s*人\\s*已?经?购?买");
	    Pattern p2 = Pattern.compile("人数?:(\\d+)");
	    
	    Matcher m1 = p1.matcher(str);
	    Matcher m2 = p2.matcher(str);
	    String numStr = null;
	    if (m1.find()) {
	        numStr = m1.group(1);
	    } else if (m2.find()) {
	        numStr = m2.group(1);
	    }
	    if (numStr != null) {
	        return Integer.parseInt(numStr);
	    } 
	    return -1;
	}
	public static Double getPrice(String str) {
	    Double origPrice = ItemUtils.getOrigPrice(str);
	   
        Pattern p = Pattern.compile("(\\d+\\.?\\d+)元");
        Matcher m = p.matcher(str);
        List<Double> priceList = new ArrayList<Double>();
        while (m.find()) {
            String priceStr = m.group(1);
            Double price = null;
            try {
                price = Double.parseDouble(priceStr);
                if (origPrice == null) {
                	priceList.add(price);
                }
                else if (origPrice != null && price < origPrice)
                	return price;
            } catch (Exception e) {}
        }
        if (priceList.size() == 2) {
        	if (priceList.get(0) < priceList.get(1)) {
        		return priceList.get(0);
        	}
        	else if (priceList.get(1) < priceList.get(0))
        		return priceList.get(1);
        }
        
        p = Pattern.compile("￥(\\d+\\.?\\d+)");
         m = p.matcher(str);
        while (m.find()) {
            String priceStr = m.group(1);
            Double price = null;
            try {
                price = Double.parseDouble(priceStr);
                if (origPrice == null || price < origPrice)
                	return price;
            } catch (Exception e) {}
        }
        
		Pattern p1 = Pattern.compile("现价|售\\s*(\\d+\\.?\\d+)元?");
		Pattern p2 = Pattern.compile("仅售\\s*(\\d+\\.?\\d+)元?");
		Matcher m1 = p1.matcher(str);
		if (m1.find()) {
			String price = m1.group(1);
			try {
				return Double.parseDouble(price);
			}
			catch (Exception e) {
			}
		}
		
		m1 = p2.matcher(str);
		if (m1.find()) {
			String price = m1.group(1);
			try {
				return Double.parseDouble(price);
			}
			catch (Exception e) {
				return null;
			}
		}
		
		return null;
	}
	
	public static Double extractDigits(String str) {
	    Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return Double.parseDouble(m.group(0));
        }
        return null;
	}
	
	public static boolean validate(TuanGouItemData item) {
		if (item.getTitle() != null
				&& item.getPrice() != null
				&& item.getImage() != null
				&& item.getOrigPrice() != null
				&& item.getPrice() < item.getOrigPrice())
		{
			return true;
		}
		
		return false;
	}
	
	public static String sortByOrderNumDesc(TuanGouItemData[] items) {
		class ComparatorByOrderNum implements Comparator<TuanGouItemData> {
			//@Override
			public int compare(TuanGouItemData t1,
					TuanGouItemData t2) {
				if (t1.getOrderNum() < t2.getOrderNum())
					return 1;
				else if (t1.getOrderNum() > t2.getOrderNum())
					return -1;
				return 0;
			}
		}
	      if (items.length <= 1)
	            return "";
		 Arrays.sort(items, new ComparatorByOrderNum());
		 StringBuilder sb = new StringBuilder();
		 for (TuanGouItemData item : items ) {
			 sb.append(item.getId() + ",");
		 }
		 return sb.substring(0, sb.length()-1);
	
	}
	
	public static String sortByPrice(TuanGouItemData[] items) {
		class ComparatorByPrice implements Comparator<TuanGouItemData> {
			//@Override
			public int compare(TuanGouItemData t1,
					TuanGouItemData t2) {
				if (t1.getPrice() < 0)
					return 1;
				if (t2.getPrice() < 0)
					return -1;
				if (t1.getPrice() < t2.getPrice())
					return -1;
				else if (t1.getPrice() > t2.getPrice())
					return 1;
				return 0;
			}
		}
		if (items.length <= 1)
		    return "";
		 Arrays.sort(items, new ComparatorByPrice());
		 StringBuilder sb = new StringBuilder();
		 for (TuanGouItemData item : items ) {
			 sb.append(item.getId() + ",");
		 }
		 
		 return sb.substring(0, sb.length()-1);
	}
	
	public static String sortBySavePriceDesc(TuanGouItemData[] items) {
		class ComparatorBySavePrice implements Comparator<TuanGouItemData> {
			
			public int compare(TuanGouItemData t1,
					TuanGouItemData t2) {
				if (t1.getSavePrice() > t2.getSavePrice())
					return -1;
				else if (t1.getSavePrice() < t2.getSavePrice())
					return 1;
				return 0;
			}
		}
		if (items.length <= 1)
	            return "";
		 Arrays.sort(items, new ComparatorBySavePrice());
		 StringBuilder sb = new StringBuilder();
	     
		 for (TuanGouItemData item : items ) {
			 sb.append(item.getId() + ",");
		 }
		 return sb.substring(0, sb.length()-1);
	}

	public static String sortByDiscount(TuanGouWebItem[] items) {
		class ComparatorByDiscount implements Comparator<TuanGouItemData> {
			//@Override
			public int compare(TuanGouItemData t1,
					TuanGouItemData t2) {
				if (t1.getDiscount() < t2.getDiscount())
					return -1;
				else if (t1.getDiscount() > t2.getDiscount())
					return 1;
				return 0;
			}
		}
	     if (items.length <= 1)
	            return "";
		 Arrays.sort(items, new ComparatorByDiscount());
		 StringBuilder sb = new StringBuilder();
		 for (TuanGouItemData item : items ) {
			 sb.append(item.getId() + ",");
		 }
		 return sb.substring(0, sb.length()-1);
	}
	
}
